﻿using System;
using System.Collections.Generic;
using ch05.binary;
using ch05.binary.interpreter;
using ch05.binary.wasm_reader;
using ch05.cmd;

namespace ch05
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: wasmgo [-d] filename");
                Environment.Exit(0);
            }

            if (args[0] == "-d")
            {
                var (module, err) = WasmReader.DecodeFile(args[1]);
                Dumper.Dump(module);
            }
            else
            {
                var (module, err) = WasmReader.DecodeFile(args[0]);
                ExecMainFunc(ref module);
            }
        }

        private static void ExecMainFunc(ref Module module)
        {
            var idx = (int) (module.StartSec) - (module.ImportSec.Length);
            var stack = new Stack<ulong>();
            var op = new OperandStack(stack);
            var vm = new Vm(op, module);
            vm.ExecCode(idx);
        }
    }
}